﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using PlugNT.Custom;
using PlugNT.Cms.Core;
using PlugNT.Cms.BLL;
using PlugNT.Cms.Model;
using PlugNT.Cms.Page;

namespace PlugNT.Cms.Web.Admin.Pre_Article
{
    public partial class Edit : AdminPage
    {
        private Category curCategory = new Category();
        private Article curArticle = new Article();
        private Field curField = new Field();
        private Channel curChannel = new Channel();
        private Tables curTables = new Tables();
        private const string bindtag = "bindtag";

        private string currpostfix = "";
        //public string jsonString = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //权限检测
            this.CheckPower();

            currpostfix = (Request.QueryString["currpostfix"] == null) ? WebConfig.TablePostfix : Request.QueryString["currpostfix"].Trim();
            curArticle.CurPostfix = currpostfix;
            if (!IsPostBack)
            {
                //上次请求路径
                if (hidReferrer.Value.Trim() == "")
                {
                    Uri uri = Request.UrlReferrer;
                    if (uri != null)
                    {
                        hidReferrer.Value = uri.ToString();
                    }
                }
                //绑定数据
                Data_bind();
            }
        }

        protected void imgBtnSubmit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
            ArticleInfo model = null;
            int id = -1;
            string title = this.txttitle.Text;
            bool flag = true;
            string errorMessage = "修改新闻--<b>[" + title + "]</b>--失败！&z=no";

            if (tinfo != null)
            {
                if (Request.QueryString["id"] != null)
                {
                    id = int.Parse(Request.QueryString["id"]);
                    model = curArticle.GetArticleInfo(id);
                }
                if (model != null)
                {
                    string images = this.txtpic.Text;
                    string subtitle = this.txtsubtitle.Text;
                    string jumpurl = (this.jumpurl_on_of.Checked) ? this.jumpurl.Text.Trim() : "";

                    string[] clsArr = this.Request.Form["ddlMenu"].Trim().Split('-');
                    if (clsArr.Length == 3)
                    {
                        string clslist = clsArr[0];
                        string clsno = clsArr[1];
                        bool isbindtmp = (clsArr[2] == bindtag);

                        //生成路径
                        string createpath = txtcreatepath.Text.Trim();
                        string t_createpath = "";
                        string t_showfile = "";

                        Templet tmpTemplet = new Templet();
                        DataTable dtTemplet = tmpTemplet.GetListByClsno(clsno);
                        if (dtTemplet.Rows.Count > 0)
                        {
                            DataRow drTemplet = dtTemplet.Rows[0];
                            t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                            t_createpath = t_createpath + drTemplet["createpath"].ToString();
                            t_showfile = drTemplet["showfile"].ToString();
                        }

                        model.images = images;
                        model.title = title;
                        model.subtitle = subtitle;
                        model.keyword = this.keyword.Text;//默认值
                        model.description = this.txtzhaiyao.Text;
                        model.clsno = clsno;
                        if (this.hidClsno.Value != clsno)
                        {
                            model.clslist = clslist;  //curChannel.GetClslistByNo(clsno, false);
                        }
                        model.contents = this.txtContext.Text;
                        model.jumpurl = jumpurl;
                        model.info = this.txtinfor.Text;
                        model.author = this.txtauthor.Text;
                        model.url = this.txturl.Text;
                        model.tip = int.Parse(this.txtdig.Text.Trim());
                        model.tag = this.txttag.Text;
                        model.hits = int.Parse(this.txthits.Text.Trim());
                        model.orders = int.Parse(txtorders.Text.Trim());
                        model.commend = this.commend.Checked;
                        model.stick = this.stick.Checked;
                        model.publish = this.publish.Checked;
                        model.createpath = (createpath == "") ? t_createpath : "/" + createpath.Trim('/') + "/";
                        model.pagename = txtpagename.Text.Trim();

                        if (!"".Equals(jumpurl))
                        {
                            model.jumpurl = createpath;
                            model.createpath = jumpurl;
                            model.pagename = "' target='_blank' p='";
                        }
                        //设置扩展字段
                        if (Request.Form != null)
                        {
                            foreach (string s in Request.Form.Keys)
                            {
                                if (s.StartsWith("extfield_"))
                                {
                                    FieldModel finfo = new FieldModel();
                                    string[] sArr = s.Split('_');
                                    finfo.fieldName = sArr[1];
                                    finfo.fieldType = sArr[2];
                                    finfo.fieldValue = Request.Form[s];
                                    model.AppExtField(finfo);
                                }
                            }
                        }

                        //更新页面名
                        if (model.pagename == "")
                        {
                            string tmpFileName = PlugNT.Common.Utils.GetFileName(t_showfile);
                            int tmpFlag = tmpFileName.LastIndexOf(".");
                            tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                            string cmsPreShow = tmpFileName;
                            model.pagename = cmsPreShow + id.ToString();
                        }
                        DataRow dr = curArticle.GetPreviousDataRow(model.id, model.clsno);
                        if (dr != null)
                        {
                            string hurl = (dr["jumpurl"].ToString() != "") ? dr["jumpurl"].ToString() : dr["createpath"].ToString() + dr["pagename"].ToString() + ".shtml";
                            model.previouspage = "<a id=\"pntPrevious" + model.id.ToString() + "\" href=\"" + hurl + "\">" + dr["title"].ToString() + "</a>";
                        }
                        else
                        {
                            model.previouspage = "";
                        }
                        dr = curArticle.GetNextDataRow(model.id, model.clsno);
                        if (dr != null)
                        {
                            string hurl = (dr["jumpurl"].ToString() != "") ? dr["jumpurl"].ToString() : dr["createpath"].ToString() + dr["pagename"].ToString() + ".shtml";
                            model.nextpage = "<a id=\"pntNext" + model.id.ToString() + "\" href=\"" + hurl + "\">" + dr["title"].ToString() + "</a>";
                        }
                        else
                        {
                            model.nextpage = "";
                        }

                        //更新数据库内容
                        if (curArticle.Update(model))
                        {
                            if (this.publish.Checked)
                            {
                                if ("".Equals(jumpurl))
                                {
                                    if (isbindtmp)
                                    {
                                        //生成静态页面
                                        HtmlBuilder html = new HtmlBuilder();
                                        html.TablePostFix = currpostfix;
                                        string error = PageBuilder.CreateShowHtml(html, id.ToString(), model.pagename, model.createpath, t_showfile, clsno);
                                        if (error != "")
                                        {
                                            errorMessage = "发布失败：" + error + "，修改新闻--<b>[" + title + "]</b>--成功！&z=no";
                                            flag = false;
                                        }
                                    }
                                }
                            }
                            if ((!this.publish.Checked) || (!isbindtmp))
                            {
                                //如果不发布则删除文件
                                string filepath = Server.MapPath("/") + model.createpath + model.pagename + ".shtml";
                                if (File.Exists(filepath))
                                {
                                    File.Delete(filepath);
                                }
                            }
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    else
                    {
                        errorMessage = "修改新闻--<b>[" + title + "]</b>--失败，请选择正确的栏目！&z=no";
                        flag = false;
                    }
                }
                else
                {
                    errorMessage = "修改新闻--<b>[" + title + "]</b>--失败，非法访问或数据库中没有该数据！&z=no";
                    flag = false;
                }
            }
            else
            {
                errorMessage = "修改新闻--<b>[" + title + "]</b>--失败，不存在数据表！&z=no";
                flag = false;
            }

            //判断跳转
            if (flag)
            {
                if (Sys.Info.articleupdated == false)
                {
                    Sys.Info.articleupdated = true;
                    Sys.UpdateArticleupdated();
                }
                string refurl = hidReferrer.Value.Trim();
                if (refurl == "" || refurl == this.Request.Path.Trim())
                {
                    Response.Redirect("../Message.aspx?message=修改新闻--<b>[" + title + "]</b>--成功！" + "&z=yes");
                }
                else
                {
                    Response.Redirect(refurl);  //跳转到管理列表页面
                }
            }
            else
            {
                Response.Redirect("../Message.aspx?message=" + errorMessage);
            }
        }

        #region 数据绑定
        private void Data_bind()
        {
            if (Request.QueryString["id"] != null)
            {
                int id = int.Parse(Request.QueryString["id"]);
                DataRow mdr = curArticle.GetDataRow(id);

                if (mdr != null)
                {

                    txtpic.Attributes.Add("onmouseover", "ShowPic(true);");
                    txtpic.Attributes.Add("onmouseout", "ShowPic(false);");
                    txtcreatepath.Attributes.Add("onpropertychange", "SwapTextColor('txtcreatepath');");
                    txtpagename.Attributes.Add("onpropertychange", "SwapTextColor('txtpagename');");

                    #region 绑定栏目

                    TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
                    if (tinfo != null)
                    {
                        DataTable dt = new Channel().GetOrderList(tinfo.bindclslist);
                        this.ddlMenu.Items.Clear();
                        this.ddlMenu.Items.Add(new ListItem("请选择所属栏目", ""));
                        foreach (DataRow dr in dt.Rows)
                        {

                            int ClassTj = Convert.ToInt32(dr["clslistlen"]);
                            string tmpClsno = dr["clsno"].ToString().Trim();
                            string tmpClslist = dr["clslist"].ToString().Trim();
                            string showfile = dr["showfile"].ToString().Trim();
                            string ClassName = dr["clsname"].ToString().Trim();
                            if (ClassTj != 1)
                            {
                                ClassName = "├ " + ClassName;
                                ClassName = PlugNT.Common.Utils.StringOfChar(ClassTj - 1, "　") + ClassName;
                            }
                            tmpClslist = tmpClslist + "-" + tmpClsno + "-" + (showfile == "" ? "null" : bindtag);
                            ListItem li = new ListItem(ClassName, tmpClslist);
                            if (showfile == "")
                            {
                                li.Attributes.Add("style", "background-color:#ffdfe2;");
                            }
                            if (mdr["clslist"].ToString() == dr["clslist"].ToString())
                            {
                                li.Selected = true;
                            }
                            this.ddlMenu.Items.Add(li);
                        }
                    }

                    #endregion

                    #region 绑定内容

                    this.txtpic.Text = mdr["images"].ToString();
                    this.txttitle.Text = mdr["title"].ToString();
                    this.txtsubtitle.Text = mdr["subtitle"].ToString();
                    if (mdr["jumpurl"].ToString().Trim() != "")
                    {
                        this.jumpurl_on_of.Checked = true;
                        //this.jumpurl.Text = mdr["jumpurl"].ToString();
                        this.jumpurl.Text = mdr["createpath"].ToString();
                    }
                    else
                    {
                        this.jumpurl_on_of.Checked = true;
                        this.jumpurl.Text = mdr["jumpurl"].ToString();
                    }
                    this.txtorders.Text = mdr["orders"].ToString();
                    this.commend.Checked = (bool)mdr["commend"];
                    this.stick.Checked = (bool)mdr["stick"];
                    this.publish.Checked = (bool)mdr["publish"];
                    this.keyword.Text = mdr["keyword"].ToString();//默认值
                    this.txtzhaiyao.Text = mdr["description"].ToString();
                    //this.ddlMenu.SelectedValue = mdr["clsno; //设置栏目



                    this.hidClsno.Value = mdr["clsno"].ToString();
                    this.txtContext.Text = mdr["contents"].ToString();
                    this.txtinfor.Text = mdr["info"].ToString();
                    this.txtauthor.Text = mdr["author"].ToString();
                    this.txturl.Text = mdr["url"].ToString();
                    this.txtdig.Text = mdr["tip"].ToString();
                    this.txthits.Text = mdr["hits"].ToString();
                    this.txttag.Text = mdr["tag"].ToString();
                    if (mdr["jumpurl"].ToString().Trim() != "")
                    {
                        this.txtcreatepath.Text = mdr["jumpurl"].ToString();
                    }
                    else
                    {
                        this.txtcreatepath.Text = mdr["createpath"].ToString();

                    }

                    this.txtpagename.Text = mdr["pagename"].ToString();


                    //绑定扩展字段
                    DataTable dt3 = curField.GetList(currpostfix);
                    if (dt3.Rows.Count > 0)
                    {
                        bool brFlag = false;
                        foreach (DataRow dr in dt3.Rows)
                        {
                            System.Web.UI.HtmlControls.HtmlGenericControl span = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                            span.InnerHtml = (brFlag ? "<br /><br />" : "") + dr["title"].ToString() + ": <br />";
                            brFlag = true;
                            div_extend.Controls.Add(span);

                            TextBox tmpTextBox = null;
                            string tmpmdrVale = mdr[dr["column"].ToString()].ToString();
                            string htmldepth = dr["htmldepth"].ToString();
                            switch (dr["htmltype"].ToString())
                            {
                                case FieldHtmlType.textType:
                                    tmpTextBox = new TextBox();
                                    if (htmldepth != "")
                                    {
                                        string[] hdepth = htmldepth.Split('*');
                                        string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                        string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                        tmpTextBox.Attributes.Add("style", widthString + heightString);
                                    }
                                    tmpTextBox.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                                    tmpTextBox.Text = (tmpmdrVale == "") ? dr["defaultvalue"].ToString() : tmpmdrVale;
                                    div_extend.Controls.Add(tmpTextBox);
                                    break;
                                case FieldHtmlType.textareaType:
                                    tmpTextBox = new TextBox();
                                    tmpTextBox.TextMode = TextBoxMode.MultiLine;
                                    if (htmldepth != "")
                                    {
                                        string[] hdepth = htmldepth.Split('*');
                                        string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                        string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                        tmpTextBox.Attributes.Add("style", widthString + heightString);
                                    }
                                    tmpTextBox.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                                    tmpTextBox.Text = (tmpmdrVale == "") ? dr["defaultvalue"].ToString() : tmpmdrVale;
                                    div_extend.Controls.Add(tmpTextBox);
                                    break;
                                case FieldHtmlType.dropdownlistType:
                                    DropDownList tmpDropDownList = new DropDownList();
                                    if (htmldepth != "")
                                    {
                                        string[] hdepth = htmldepth.Split('*');
                                        string widthString = (hdepth[0] == "") ? "" : " width:" + hdepth[0] + "px;";
                                        string heightString = (hdepth[1] == "") ? "" : " height:" + hdepth[1] + "px;";
                                        tmpDropDownList.Attributes.Add("style", widthString + heightString);
                                    }
                                    tmpDropDownList.ID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                                    DataTable dt4 = null;
                                    if (Boolean.Parse(dr["isbindsub"].ToString()))
                                    {
                                        dt4 = curCategory.GetOrderList(dr["bindclslist"].ToString());
                                    }
                                    else
                                    {
                                        dt4 = curCategory.GetOrderSubList(dr["bindclslist"].ToString());
                                    }
                                    foreach (DataRow dr2 in dt4.Rows)
                                    {

                                        int ClassTj = Convert.ToInt32(dr2["clslistlen"]);
                                        string tmpClslist = dr2["clslist"].ToString().Trim();
                                        string ClassName = dr2["clsname"].ToString().Trim();
                                        ListItem li = null;
                                        if (ClassTj == 1)
                                        {
                                            li = new ListItem(ClassName, tmpClslist);
                                        }
                                        else
                                        {
                                            ClassName = "├ " + ClassName;
                                            ClassName = PlugNT.Common.Utils.StringOfChar(ClassTj - 1, "　") + ClassName;
                                            li = new ListItem(ClassName, tmpClslist);
                                        }
                                        tmpDropDownList.Items.Add(li);
                                    }
                                    tmpDropDownList.SelectedValue = (tmpmdrVale == "") ? dr["defaultvalue"].ToString() : tmpmdrVale;
                                    div_extend.Controls.Add(tmpDropDownList);
                                    break;
                                case FieldHtmlType.editerType:
                                    string tmpEditerID = "extfield_" + dr["column"].ToString() + "_" + dr["coltype"].ToString();
                                    System.Web.UI.HtmlControls.HtmlGenericControl editer = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                                    tmpmdrVale = (tmpmdrVale == "") ? dr["defaultvalue"].ToString() : tmpmdrVale;

                                    StringBuilder sb2 = new StringBuilder();
                                    sb2.AppendLine("<textarea id=\"" + tmpEditerID + "\" name=\"" + tmpEditerID + "\">" + tmpmdrVale + "</textarea>");
                                    sb2.AppendLine("<script type=\"text/javascript\">");
                                    sb2.AppendLine("var oFCK" + tmpEditerID + " = new FCKeditor(\"" + tmpEditerID + "\"); ");
                                    sb2.AppendLine("oFCK" + tmpEditerID + ".BasePath = \"/Tools/Editer/fck/\"; ");
                                    if (htmldepth != "")
                                    {
                                        string[] hdepth = htmldepth.Split('*');
                                        if (hdepth[0] != "")
                                        {
                                            sb2.AppendLine("oFCK" + tmpEditerID + ".Width = " + hdepth[0] + "; ");
                                        }
                                        if (hdepth[1] == "")
                                        {
                                            sb2.AppendLine("oFCK" + tmpEditerID + ".Height = " + hdepth[1] + "; ");
                                        }
                                    }
                                    sb2.AppendLine("oFCK" + tmpEditerID + ".ToolbarSet = \"CustomSimple\";  ");
                                    sb2.AppendLine("oFCK" + tmpEditerID + ".ReplaceTextarea();");
                                    sb2.AppendLine("</script>");
                                    editer.InnerHtml = sb2.ToString();

                                    div_extend.Controls.Add(editer);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    else
                    {
                        System.Web.UI.HtmlControls.HtmlGenericControl editer = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
                        editer.InnerHtml = "暂无扩展字段！";
                        div_extend.Controls.Add(editer);
                    }
                    #endregion
                }
                else
                {
                    Response.Redirect("../Message.aspx?message=该记录不存在或已被删除！" + "&z=no");
                }

            }
            else
            {
                Response.Redirect("../Message.aspx?message=非法操作，请从正确的入口修改！" + "&z=no");
            }
        }


        #endregion



    }
}

